/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.project.engineering.logger;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import pl.project.engineering.data.MailServerConfig;
import pl.project.engineering.entities.AlertEmailAddress;
import pl.project.engineering.services.AppConfig;

@Slf4j
public class MailAppenderCreator {

  public void createMailAppender(AppConfig appConfig) {
    Logger rootLogger = Logger.getRootLogger();
    MailServerConfig mailSrv = appConfig.getMailServerConfig();

    GmailSMTPAppender mailAppender = (GmailSMTPAppender) rootLogger.getAppender("mailAppender");
    if (mailAppender != null) {
      rootLogger.removeAppender(mailAppender);
      mailAppender.close();
    }

    mailAppender = new GmailSMTPAppender();

    try {
      mailAppender.setName("mailAppender");
      mailAppender.setBufferSize(1);
      mailAppender.setSMTPHost(mailSrv.getSmtpHost());
      mailAppender.setSMTPUsername(mailSrv.getUsername());
      mailAppender.setSMTPPassword(mailSrv.getPassword());
      mailAppender.setSMTPPort(Integer.parseInt(mailSrv.getPort()));
      mailAppender.setFrom(mailSrv.getUsername());

      List<String> email = Lists.transform(appConfig.getAlertEmailAddressList().getAlertEmailAddresses(), new Function<AlertEmailAddress, String>() {
        @Override
        public String apply(AlertEmailAddress aea) {
          return aea.getEmail();
        }
      });

      mailAppender.setTo(Joiner.on(',').skipNulls().join(email));
      mailAppender.setSubject("WARNING sensor parameter");
      
      System.setProperty("fi.reaktor.log4j.emailthrottle.emailIntervalInSecs", new Integer(mailSrv.getEmailInterval().getValue()).toString());
      mailAppender.setEvaluatorClass("fi.reaktor.log4j.emailthrottle.ErrorEmailThrottle");
      mailAppender.setLayout(new PatternLayout("%d{dd-MM-yy HH:mm:ss:SSS} - {%p} %c{2} Thread [%t]; %x %m%n"));

      mailAppender.activateOptions();
      
      log.info("Adding mail appender");
      rootLogger.addAppender(mailAppender);
    } catch (Exception e) {
      log.error("Faild to add emergency mail appender", e);
    }
  }
}
